/**
 * fileName: AccordionTag.java
 *     Date: 2012-6-16
 **/
package com.stranger.common.tag.accordion;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.Tag;



/**
 * @作者 stranger.lin
 * 
 * @时间 2012-6-16
 */
public class AccordionTag extends BodyTagSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3092243143877461394L;

	private String id;
	private String name;
	private 	JspWriter out;
	
	@Override
	public void setBodyContent(BodyContent b) {
		this.bodyContent=b;
		
	}
	
	@SuppressWarnings("deprecation")
	@Override
	public int doStartTag() throws JspException {
		try {
			if (out==null) {
				out=pageContext.getOut();
			}
			Tag tag=findAncestorWithClass(this, AccordionsTag.class);
			if (tag==null) {
				throw new JspException("accordion标签必须在accordions标签内");
			}
			if (id==null||"".equals(id.trim())) {
				throw new JspException("id 不能为空");
			}
			if (name==null||"".equals(name.trim())) {
				name=id;
			}
			AccordionsTag accordionsTag=(AccordionsTag)tag;
			
			Accordion accordion=new Accordion();
			accordion.setId(id);
			accordion.setName(name);
			
			accordionsTag.getAccordions().add(accordion);
			
			StringBuffer html=new StringBuffer("<h3><a href=\"#\">"+name+"</a></h3>");
			html.append("<div>");
			out.print(html);
			out.flush();
			
		} catch (Exception e) {
			throw new JspException(e.getMessage());
		}
		return EVAL_PAGE;
	}

	@Override
	public int doEndTag() throws JspException {
		try {
			if (out==null) {
				out=pageContext.getOut();
			}
			StringBuffer html=new StringBuffer();
			if (bodyContent!=null) {
				html.append(bodyContent.getString());
			}
			html.append("</div>");
			out.print(html);
			out.flush();
		} catch (Exception e) {
			throw new JspException(e.getMessage());
		}
		
		return EVAL_PAGE;
	}
	
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	
	

}
